package com.geek.config.servlet.init;

import com.geek.config.convert.StringConvert;
import com.geek.config.microprofile.source.ServletContextConfigSource;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.eclipse.microprofile.config.spi.ConfigSource;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Set;

/**
 * @Author: ysq
 * @Date: 2021/7/14
 * @Description: 在Tomcat环境, 编写Servlet程序, 通过JNDI 加载全局的config
 * JNDI配置: src/main/resources/services/javax.servlet.ServletContainerInitializer
 * 数据源配: src/main/webapp/META-INF/context.xml
 */
public class ServletContextInitializer implements ServletContainerInitializer {
  @Override
  public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
    final ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
    final Config config = configProviderResolver.getBuilder()
            .addDefaultSources()
            .addDiscoveredConverters()
            .withSources(new ServletContextConfigSource(ctx))
            .withConverters(new StringConvert())
            .build();
    for (ConfigSource configSource : config.getConfigSources()) {
      for (String name : configSource.getPropertyNames()) {
        System.out.println(name);
      }
    }
    configProviderResolver.registerConfig(config, getClass().getClassLoader());
  }
}